package threadcoreknowledge.stopthreads;

/**
 * 每次循环都会调用sleep或wait等方法，那么不需要每次迭代都检查是否已中断
 * https://javaweixin6.blog.csdn.net/article/details/108068653
 */
public class RightWayStopThreadWithSleepEveryLoop {

    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            int num = 0;
            try {

                // try包裹while  会抛异常终止程序
                while (num <= 10000) {
                    if (num % 100 == 0) {
                        System.out.println(num + "是100的倍数");
                    }
                    num++;

                    //每一次循环,休眠10ms
                    Thread.sleep(10);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();

        //此处的  Thread.sleep(5000); 是休眠主线程, 让子线程运行5s,
        //子线程运行5s后, 给出子线程的休眠信号
        Thread.sleep(5000);
        thread.interrupt();
    }

}
